package com.ikingtech.platform.service.oidc.web;

import com.ikingtech.platform.service.oidc.converter.OidcResponseConverter;
import com.ikingtech.platform.service.oidc.endpoint.OidcEndpoint;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class OidcAuthorizationFilter extends OncePerRequestFilter {

    private final List<OidcResponseConverter> converters;

    private final List<OidcEndpoint> endpoints;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        for (OidcEndpoint endpoint : this.endpoints) {
            if (endpoint.support(request.getRequestURI())) {
                OidcAuthorizationResponse oidcResponse = endpoint.authorization(request);
                for (OidcResponseConverter responseConverter : this.converters) {
                    if (responseConverter.support(oidcResponse)) {
                        responseConverter.convert(oidcResponse, response);
                        return;
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
